package com.promise.jokerdream.ui.components

import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.promise.jokerdream.ui.theme.AppFontSizes
import kotlinx.coroutines.delay

/**
 * 时间输入字段组件
 * 类似验证码输入框的样式，用于输入 HH:mm 格式的时间
 * 每个数字都有独立的输入框
 */
@Composable
fun TimeInputField(
    time: String,
    onTimeChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    validateOnChange: Boolean = false, // 是否在输入时实时校验
    onValidationResult: (Boolean) -> Unit = {}, // 校验结果回调
    triggerValidation: Int = 0, // 外部触发校验的计数器
    minTime: String = "00:00", // 最小时间限制
    maxTime: String = "23:59"  // 最大时间限制
) {
    var hour1 by remember { mutableStateOf("") }
    var hour2 by remember { mutableStateOf("") }
    var minute1 by remember { mutableStateOf("") }
    var minute2 by remember { mutableStateOf("") }
    var currentFocus by remember { mutableStateOf(0) } // 0: hour1, 1: hour2, 2: minute1, 3: minute2
    var inputText by remember { mutableStateOf("") } // 当前输入的文本
    var hasError by remember { mutableStateOf(false) } // 是否有输入错误
    
    // 焦点请求器
    val focusRequester = remember { FocusRequester() }

    val shakeOffset = remember { Animatable(0f) }

    // 初始化时间值
    LaunchedEffect(time) {
        if (time.isNotEmpty() && time.contains(":")) {
            val parts = time.split(":")
            if (parts.size == 2) {
                val hour = parts[0].padStart(2, '0')
                val minute = parts[1].padStart(2, '0')
                hour1 = hour[0].toString()
                hour2 = if (hour.length > 1) hour[1].toString() else ""
                minute1 = minute[0].toString()
                minute2 = if (minute.length > 1) minute[1].toString() else ""
            }
        }
    }

    // 将时间字符串转换为分钟数
    fun timeToMinutes(time: String): Int {
        val parts = time.split(":")
        if (parts.size != 2) return 0
        val hour = parts[0].toIntOrNull() ?: 0
        val minute = parts[1].toIntOrNull() ?: 0
        return hour * 60 + minute
    }
    
    // 检查时间是否在指定范围内
    fun isTimeInRange(time: String, min: String, max: String): Boolean {
        val timeMinutes = timeToMinutes(time)
        val minMinutes = timeToMinutes(min)
        val maxMinutes = timeToMinutes(max)
        return timeMinutes in minMinutes..maxMinutes
    }
    
    // 验证时间输入
    fun validateTime(): Boolean {
        val hour = "$hour1$hour2".toIntOrNull() ?: 0
        val minute = "$minute1$minute2".toIntOrNull() ?: 0
        
        // 基本格式验证
        if (hour !in 0..23 || minute !in 0..59) {
            return false
        }
        
        // 时间范围验证
        val currentTimeString = String.format("%02d:%02d", hour, minute)
        return isTimeInRange(currentTimeString, minTime, maxTime)
    }
    
    // 更新父组件的时间值
    LaunchedEffect(hour1, hour2, minute1, minute2) {
        val hour = "$hour1$hour2".padStart(2, '0')
        val minute = "$minute1$minute2".padStart(2, '0')
        val isValid = validateTime()
        
        onTimeChange("$hour:$minute")
        onValidationResult(isValid)
        
        if (validateOnChange) {
            if (isValid) {
                hasError = false
            } else {
                hasError = true
            }
        }
    }

    // 处理输入文本变化
    LaunchedEffect(inputText) {
        if (inputText.isNotEmpty() && inputText.all { it.isDigit() }) {
            when (currentFocus) {
                0 -> {
                    hour1 = inputText.take(1)
                    if (inputText.length >= 1) {
                        currentFocus = 1
                        inputText = ""
                    }
                }
                1 -> {
                    hour2 = inputText.take(1)
                    if (inputText.length >= 1) {
                        currentFocus = 2
                        inputText = ""
                    }
                }
                2 -> {
                    minute1 = inputText.take(1)
                    if (inputText.length >= 1) {
                        currentFocus = 3
                        inputText = ""
                    }
                }
                3 -> {
                    minute2 = inputText.take(1)
                    if (inputText.length >= 1) {
                        inputText = ""
                    }
                }
            }
        }
    }
    
    // 外部触发校验
    LaunchedEffect(triggerValidation) {
        if (triggerValidation > 0) {
            val isValid = validateTime()
            onValidationResult(isValid)
            if (isValid) {
                hasError = false
            } else {
                hasError = true
                // 左右抖动
                repeat(3) {
                    shakeOffset.animateTo(10f, tween(50))
                    shakeOffset.animateTo(-10f, tween(50))
                }
                shakeOffset.animateTo(0f, tween(50))
                // 2秒后清除错误状态
                delay(2000)
                hasError = false
            }
        }
    }
    
    // 抖动效果（仅在实时校验模式下使用）
    LaunchedEffect(hasError) {
        if (hasError && validateOnChange) {
            // 左右抖动
            repeat(3) {
                shakeOffset.animateTo(10f, tween(50))
                shakeOffset.animateTo(-10f, tween(50))
            }
            shakeOffset.animateTo(0f, tween(50))
            // 2秒后清除错误状态
            delay(2000)
            hasError = false
        }
    }

    // 自动聚焦
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }

    Box(
        modifier = modifier
    ) {
        // 隐藏的 TextField 用于键盘输入
        TextField(
            value = inputText,
            onValueChange = { inputText = it },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            singleLine = true,
            modifier = Modifier
                .fillMaxWidth()
                .focusRequester(focusRequester)
                .alpha(0f), // 完全透明
            colors = TextFieldDefaults.colors(
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                disabledIndicatorColor = Color.Transparent,
                focusedContainerColor = Color.Transparent,
                unfocusedContainerColor = Color.Transparent,
                disabledContainerColor = Color.Transparent
            )
        )
        
        // 显示的时间输入框
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .graphicsLayer {
                    translationX = shakeOffset.value
                },
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 小时十位
            TimeDigitDisplayBox(
                value = hour1,
                placeholder = "1",
                isFocused = currentFocus == 0,
                hasError = hasError,
                onClick = { currentFocus = 0; focusRequester.requestFocus() },
                modifier = Modifier.size(40.dp)
            )

            Spacer(modifier = Modifier.width(4.dp))

            // 小时个位
            TimeDigitDisplayBox(
                value = hour2,
                placeholder = "2",
                isFocused = currentFocus == 1,
                hasError = hasError,
                onClick = { currentFocus = 1; focusRequester.requestFocus() },
                modifier = Modifier.size(40.dp)
            )

            // 分隔符
            Text(
                text = ":",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.padding(horizontal = 8.dp)
            )

            // 分钟十位
            TimeDigitDisplayBox(
                value = minute1,
                placeholder = "0",
                isFocused = currentFocus == 2,
                hasError = hasError,
                onClick = { currentFocus = 2; focusRequester.requestFocus() },
                modifier = Modifier.size(40.dp)
            )

            Spacer(modifier = Modifier.width(4.dp))

            // 分钟个位
            TimeDigitDisplayBox(
                value = minute2,
                placeholder = "0",
                isFocused = currentFocus == 3,
                hasError = hasError,
                onClick = { currentFocus = 3; focusRequester.requestFocus() },
                modifier = Modifier.size(40.dp)
            )
        }
    }
}

/**
 * 数字显示框（纯显示，不处理输入）
 */
@Composable
private fun TimeDigitDisplayBox(
    value: String,
    placeholder: String,
    isFocused: Boolean,
    hasError: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val borderColor = when {
        hasError -> Color.Red
        isFocused -> MaterialTheme.colorScheme.primary
        else -> MaterialTheme.colorScheme.outline
    }

    Box(
        modifier = modifier
            .clip(RoundedCornerShape(8.dp))
            .background(MaterialTheme.colorScheme.surface)
            .border(
                width = 2.dp,
                color = borderColor,
                shape = RoundedCornerShape(8.dp)
            )
            .clickable { onClick() },
        contentAlignment = Alignment.Center
    ) {
        if (value.isEmpty()) {
            Text(
                text = placeholder,
                fontSize = AppFontSizes.body,
                color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
                textAlign = TextAlign.Center
            )
        } else {
            Text(
                text = value,
                fontSize = AppFontSizes.body,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                textAlign = TextAlign.Center
            )
        }
    }
}
